/********************************************************************************************
** Copyright � 2011 Nokia Corporation. All rights reserved.
** Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
** Java and all Java-based marks are trademarks or registered trademarks of
** Sun Microsystems, Inc. Other product and company names mentioned herein may be
** trademarks or trade names of their respective owners.
**
** Subject to the conditions below, you may, without charge:
**
** �  Use, copy, modify and/or merge copies of this software and
**    associated content and documentation files (the �Software�)
**
** �  Publish, distribute, sub-licence and/or sell new software
**    derived from or incorporating the Software.
**
** Some of the documentation, content and/or software maybe licensed under open source
** software or other licenses.  To the extent such documentation, content and/or
** software are included, licenses and/or other terms and conditions shall apply
** in addition and/or instead of this notice. The exact terms of the licenses, disclaimers,
** acknowledgements and notices are reproduced in the materials provided.
**
** This file, unmodified, shall be included with all copies or substantial portions
** of the Software that are distributed in source code form.
**
** The Software cannot constitute the primary value of any new software derived
** from or incorporating the Software.
**
** Any person dealing with the Software shall not misrepresent the source of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
********************************************************************************************/
import Qt 4.7

import QtMobility.location 1.1

import "dbhandler.js" as DB
import "privacysettings.js" as PS
import "DCDataClasses.js" as DCDATA

Dialog {
    id: mainwindow
    width: 550
    height: 360
    label:  "Carpool"
    z: 1
    messages: messagewin


    // -----------------------------------------------
    // traveller set
    property string follow_carpoolkarpoid: "0"
    property string follow_driveralias: ""
    property bool follow_locating_on: false
    // driver set
    property string started_gpssending_carpoolkarpoid: "0"
    property string started_carpooldriver_alias: ""

    property string driverlastlatitude: "0"
    property string driverlastlongitude: "0"
    property bool sendingthenewlocation: false
    property bool readingthenewlocation: false

    property bool simulationmodeon: false
    property int simulationindex: -1
    property variant simulationroutepolyline: []


    property string appcase: ""


    PositionSource
    {
        id: positionSource
        updateInterval: 10000 // 10 secs
        active: false

        onPositionChanged:
        {
            if (position.latitudeValid  && position.longitudeValid )
            {
                saveDriversPosition(position.coordinate.latitude,position.coordinate.longitude)
            }
            else
            {
                messagebox.text = "Not a valid location."
                messagebox.show("")
            }

        }

    }

    function saveDriversPosition(lat,lon)
    {
        driverlastlatitude = lat
        driverlastlongitude = lon


        if (!sendingthenewlocation)
        {
            sendingthenewlocation = true

            var cpcarpoolactivationlist = new DCDATA.DCCarpoolActivationsList()
            var cpcarpoolactivation = new DCDATA.DCCarpoolActivation()
            cpcarpoolactivation.carpoolkarpoid = started_gpssending_carpoolkarpoid
            cpcarpoolactivation.active = "1"
            cpcarpoolactivation.alias = started_carpooldriver_alias
            cpcarpoolactivation.lat = driverlastlatitude
            cpcarpoolactivation.lon = driverlastlongitude
            cpcarpoolactivationlist.carpoolactivationlist[0] = cpcarpoolactivation
            DCDATA.send(cpcarpoolactivationlist,settings.datacloudurl,"setcarpoolactivation",carpoolactivationcb)
        }

    }

    function carpoolactivationcb(response)
    {
        try
        {
            if (response.isError)
            {
                sendGPS("stop")
                messagebox.text = "Failed to save the coordinates.<br>Stop sending the location."
                messagebox.show("")
            }

        }
        catch (e)
        {
            console.log("carpoolactivationcb exception: " + e)
        }
        sendingthenewlocation = false
    }

    function followCarpool(state)
    {
        if (state == "start")
        {
            driverlastlatitude = "0"
            driverlastlongitude = "0"

            follow_locating_on = false
            simulationindex = -1
            simulationmodeon = false

            initMenu("following")

            getdriverlocation.start()
        }
        else
        {
            simulationindex = -1
            simulationmodeon = false
            getdriverlocation.stop()

            driverlastlatitude = "0"
            driverlastlongitude = "0"

            initMenu("loginok")
        }
    }

    function getDriverLocation()
    {
        if (!readingthenewlocation)
        {
            readingthenewlocation = true

            var cpcarpoolactivationlist = new DCDATA.DCCarpoolActivationsList()
            var cpcarpoolactivation = new DCDATA.DCCarpoolActivation()
            cpcarpoolactivation.carpoolkarpoid = follow_carpoolkarpoid
            cpcarpoolactivationlist.carpoolactivationlist[0] = cpcarpoolactivation
            DCDATA.send(cpcarpoolactivationlist,settings.datacloudurl,"getcarpoolactivation",getcarpoolsactivationcb)
        }

        if (simulationmodeon && simulationindex > -1)
        {
            var lat = driverlastlatitude
            var lon = driverlastlongitude
            if (simulationindex < simulationroutepolyline.length)
            {
                lat = simulationroutepolyline[simulationindex].latitude
                lon = simulationroutepolyline[simulationindex].longitude
                simulationindex += 5
            }
            else
            {
                lat = simulationroutepolyline[simulationroutepolyline.length-1].latitude
                lon = simulationroutepolyline[simulationroutepolyline.length-1].longitude
                simulationmodeon = false
                simulationindex = -1
                initMenu(appcase)
            }

            saveDriversPosition(lat,lon)
        }
    }

    function getcarpoolsactivationcb(response)
    {
        try
        {
            if (!response.isError && response.carpoolactivationlist.length > 0)
            {
                follow_driveralias = response.carpoolactivationlist[0].alias
                driverlastlatitude = response.carpoolactivationlist[0].lat
                driverlastlongitude = response.carpoolactivationlist[0].lon

                map.showDriverIcon(driverlastlatitude,driverlastlongitude, follow_locating_on, follow_driveralias)
            }
        }
        catch (e)
        {

        }
        readingthenewlocation = false
    }

    function sendGPS(state)
    {
        if (state == "start")
        {
            sendingthenewlocation = false
            positionSource.start()
            mainwindow.setGPSOnIconVisible(true)
        }
        else
        {
            positionSource.stop()
            mainwindow.setGPSOnIconVisible(false)
        }
    }


    function startSimulation()
    {
        simulationmodeon = true
        simulationindex = -1

        simulationroutepolyline = map.getRoutepolyline()

        if (simulationroutepolyline.length > 0)
        {
            simulationindex = 0
            started_gpssending_carpoolkarpoid = follow_carpoolkarpoid
            started_carpooldriver_alias = "SIMULATION"
        }
        else
        {
            messagebox.text = "Couldn't start the simulation.<br>Try again soon."
            messagebox.show("")
            simulationmodeon = false
        }
    }

    Timer {
        id: getdriverlocation
        interval: 5000
        running: false
        repeat: true
        onTriggered: mainwindow.getDriverLocation()
    }

    // ------------------------------------

    MessageBox
    {
        id: messagebox


    }

    Messages
    {
        id: messagewin;
        z: 999
        width: mainwindow.width
        height: mainwindow.height - mainwindow.titlerect.height
        x: 0
        y: mainwindow.titlerect.height
        datacloudurl: settings.datacloudurl
        karpoid: personalprofile.karpoid
        password: personalprofile.password

    }

    function initMenu(_appcase)
    {
        appcase = _appcase

        console.log("INITMENU: " + appcase)
        if (appcase == "loginok")
        {
            mainwindow.addMenuItems(["CarPool...","Routes...","Join trip...","My trips...","Profile...","Settings...","Login..."], false)
        }
        else if (appcase == "loginfailed")
        {
            mainwindow.addMenuItems(["Settings...","Login..."], false)
        }
        else if (appcase == "handleroute")
        {
            mainwindow.addMenuItems(["Saved...","New route...", "Back..."], false)
        }
        else if (appcase == "jointrip")
        {
            mainwindow.addMenuItems(["Back..."], false)
        }
        else if (appcase == "following" || appcase == "following_locating_off")
        {
            if (simulationmodeon)
            {
                mainwindow.addMenuItems(["Locate", "Locating ON", "Stop following","Simulation OFF"], false)
            }
            else
            {
                mainwindow.addMenuItems(["Locate", "Locating ON", "Stop following","Simulation ON"], false)
            }
        }
        else if (appcase == "following_locating_on")
        {
            if (simulationmodeon)
            {
                mainwindow.addMenuItems(["Locate", "Locating OFF", "Stop following","Simulation OFF"], false)
            }
            else
            {
                mainwindow.addMenuItems(["Locate", "Locating OFF", "Stop following","Simulation ON"], false)
            }
        }
        else
        {
            mainwindow.addMenuItems(["Settings...","Login..."], false)
        }

    }

    onMenuSelection:
    {
        if (selectionlabel == "CarPool...")
        {
            if (!carpool.visible)
            {
                carpool.initAndShow()
            }
        }
        else if (selectionlabel == "Routes...")
        {
            initMenu("handleroute");
            map.setHandleroutes(true)
        }
        else if (selectionlabel == "Join trip...")
        {
            map.setJointrip(true)
            initMenu("jointrip");
        }
        else if (selectionlabel == "My trips...")
        {
            map.myTrips()
        }
        else if (selectionlabel == "New route...")
        {
            map.newRoute();

        }
        else if (selectionlabel == "Saved...")
        {
            map.selectRoute();

        }
        else if (selectionlabel == "Locate")
        {
            if (driverlastlatitude != "0" && driverlastlongitude != "0")
            {
                map.showDriverIcon(driverlastlatitude,driverlastlongitude, true, started_carpooldriver_alias)
            }

        }
        else if (selectionlabel == "Locating ON")
        {
            follow_locating_on = true
            initMenu("following_locating_on")
        }
        else if (selectionlabel == "Locating OFF")
        {
            follow_locating_on = false
            initMenu("following_locating_off")
        }
        else if (selectionlabel == "Stop following")
        {
            followCarpool("stop")

            if (simulationindex > -1)
            {
                sendGPS("stop")
                simulationindex = -1

            }
        }
        else if (selectionlabel == "Simulation ON")
        {
            startSimulation()
            initMenu(appcase)
        }
        else if (selectionlabel == "Simulation OFF")
        {
            simulationmodeon = false
            simulationindex = -1
            initMenu(appcase)
        }
        else if (selectionlabel == "Back...")
        {
            initMenu("loginok");
            if (map.handleroutes)
            {
                map.setHandleroutes(false)
            }
            map.setJointrip(false)

        }
        else if (selectionlabel == "Profile...")
        {
            if (!personalprofile.visible)
            {
                personalprofile.visible = true

            }
        }
        else if (selectionlabel == "Settings...")
        {
            if (!settings.visible)
            {
                settings.visible = true
            }
        }
        else if (selectionlabel == "Login...")
        {
            if (!login.visible)
            {
                login.visible = true
            }
        }

    }


    MapView
    {
        id: map

        anchors.left: parent.left
        anchors.right: parent.right
        anchors.top: mainwindow.titlerect.bottom
        anchors.bottom: parent.bottom

        datacloudurl: settings.datacloudurl
        username: personalprofile.username
        password: personalprofile.password
        karpoid: personalprofile.karpoid

        firstname: personalprofile.firstname
        lastname: personalprofile.lastname
        phonenumber: personalprofile.phone
        hometown: personalprofile.hometown

        onStartFollowingCarpool:
        {
            mainwindow.follow_carpoolkarpoid = carpoolkarpoid
            mainwindow.followCarpool("start")
        }

        onStopFollowingCarpool:
        {
            mainwindow.followCarpool("stop")
            mainwindow.follow_carpoolkarpoid = ""

        }

    }



    Login
    {
        id: login
        anchors.fill: parent
        datacloudurl: settings.datacloudurl
        messages: mainwindow.messages

        onLoginOk:
        {
            console.log("MAIN::onLoginOk()\r\n");

            login.visible = false
            var userdata = login.getData()

            // update the profile dialogs
            personalprofile.setData(userdata);

            // save the personal data also in the local database
            DB.savePersonalData(userdata)

            // save settings => logindone attribute
            settings.logindone = true;
            DB.saveSettings(settings.getData())

            mainwindow.initMenu("loginok");

            var privacysettings = {}

            privacysettings["showname"] = showname
            privacysettings["showphone"] = showphone
            privacysettings["showhometown"] = showhometown

            personalprofile.setPrivacySettings(privacysettings)
            DB.savePrivacySettings(privacysettings)
            PS.setPrivacySettings(privacysettings["showname"],privacysettings["showphone"],privacysettings["showhometown"])


        }

        onLoginCancel:
        {
            console.log("MAIN::onLoginCancel()\r\n");
            login.visible = false

            // save settings => logindone attribute
            settings.logindone = false;
            DB.saveSettings(settings.getData())

            mainwindow.initMenu("loginfailed");
        }



        visible: false
    }

    PersonalProfile
    {
        id: personalprofile
        anchors.fill: parent
        datacloudurl: settings.datacloudurl
        messages: mainwindow.messages


        onProfileOk:
        {
            personalprofile.visible = false;
            // save the personal data also in the local database
            DB.savePersonalData(getAllData())
            DB.savePrivacySettings(getPrivacyData())
            PS.setPrivacySettings(showmyname,showmyphone,showmyhometown)
        }

        onProfileCancel:
        {
            personalprofile.visible = false;
        }


        Component.onCompleted:
        {
            personalprofile.init()
        }

        visible: false
    }


    Settings
    {
        id: settings
        anchors.fill: parent
        messages: mainwindow.messages


        function privacysettingscb(data)
        {
            if (data != null)
            {
                personalprofile.setPrivacySettings(data)
                PS.setPrivacySettings(data["showname"],data["showphone"],data["showhometown"])
            }

        }

        function userdatacb(userdata)
        {
            if (userdata != null)
            {
                personalprofile.setData(userdata)
                login.setData(userdata)

                DB.getPrivacySettings(privacysettingscb)
            }
            else
            {
                console.log("FROM DB: userdata not yet saved");
            }
        }


        function settingscb(data)
        {
            DB.getPersonalData(userdatacb);
            if (data != null)
            {
                settings.setData(data)

                if (!settings.uselastlogin || !settings.logindone)
                {
                    login.visible = true;
                }
                else
                {
                    mainwindow.initMenu("loginok");
                }

            }
            else
            {
                settings.visible = true
            }
        }

        onSettingsOk:
        {
            settings.visible = false
            DB.saveSettings(settings.getData());

            if (!logindone)
            {
                login.visible = true
            }
            else
            {
                mainwindow.initMenu("loginok");
            }
        }

        onSettingsCancel:
        {
            settings.visible = false
            if (!logindone)
            {
                login.visible = true

            }
        }



        Component.onCompleted:
        {
            console.log(" -------------- SETTINGS onCompleted --------------")
            DB.getSettings(settingscb);
        }

        visible: false

    }

    CarPool
    {
        id: carpool
        messages: mainwindow.messages
        anchors.fill: parent
        datacloudurl: settings.datacloudurl
        username: personalprofile.username
        password: personalprofile.password
        karpoid: personalprofile.karpoid
        useralias: personalprofile.alias

        onOk:
        {
            carpool.visible = false
        }

        onCancel:
        {
            carpool.visible = false
        }



        onStartSendingGPS:
        {
            mainwindow.started_gpssending_carpoolkarpoid = carpoolkarpoid
            mainwindow.started_carpooldriver_alias = useralias
            mainwindow.sendGPS("start")
        }

        onStopSendingGPS:
        {
            mainwindow.sendGPS("stop")
            mainwindow.started_gpssending_carpoolkarpoid = ""
            mainwindow.started_carpooldriver_alias = ""

        }

        visible: false


    }


    Component.onCompleted:
    {
        console.log("MAIN COMPLETED")
    }
}
